﻿using Iot.Device.Pn532;
using Iot.Device.Sht3x;
using IotDeviceToolHepler;
using IotDeviceToolHepler.Device;
using IotDeviceToolHepler.Model.Device;
using IotDeviceToolHepler.Utils;
using Microsoft.EntityFrameworkCore.Metadata;
using Models.Common;
using Models.Device;
using Models.TaskPlain;
using NetTaste;
using Newtonsoft.Json;
using Org.BouncyCastle.Utilities.Encoders;
using GateWayCommonService.Device;

using System;
using System.Collections.Generic;
using System.Data;
using System.Device.I2c;
using System.Drawing.Drawing2D;
using System.IO.Ports;
using System.Text;
using System.Threading;
using UnitsNet;
using Utils_Base;
using Utils_ORM;
using Utils_ORM.MySql_IotWork;
using static Models.Common.EnumDeviceState;

namespace GateWayCommonService.GateWay
{
    public class ServiceHandleRS485
    {
        //static List<ModelRS485List> ModelRS485Lists = new List<ModelRS485List>();
        /// <summary>
        /// 执行485指令
        /// </summary>
        /// <param name="obj"></param>
        public void gateWayExecuteRS485(object obj)
        {
            MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            CommandLogModel commandLogModel = mQReqModel.toGateWayData;
            try
            {

                ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);
                ModelCommandAgreementParameter modelCommandAgreementParameter = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreement.agreementParameter);

                if (modelCommandAgreement.agreementParameter.command != null)
                {
                    List<ModelCommandAgreementParameterCommand> commandList = UtilsObject.DynamicToEntity<List<ModelCommandAgreementParameterCommand>>(modelCommandAgreement.agreementParameter.command);
                    if (commandList.Count > 0)
                    {
                        ModelCommandAgreementParameterCommand command = commandList.Where(c => c.key == commandLogModel.key).FirstOrDefault();

                        if (command != null)
                        {
                            commandLogModel.content = command.value;//自定指令   否则使用默认commandLogModel.content指令
                        }
                    }
                }
                Task.Run(() =>
                {
                    getPortDataList(obj, modelCommandAgreementParameter.portName, modelCommandAgreementParameter.baudRate, commandLogModel.content);
                });

            }
            catch (Exception ex)
            {
                ModelReceverData modelDeviceData = new ModelReceverData();
                modelDeviceData.content = ex.ToString();
                mQReqModel.respCode = ResponseCode.System_ERROR;
                mQReqModel.respMsg = MQEventEnum.Event_State_Error;
                mQReqModel.toServerData = modelDeviceData;
                new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                Console.WriteLine(ex.ToString());
            }
        }

        static List<ModelRS485QueueList> serialList = new List<ModelRS485QueueList>();
        static bool runing = false;
        static int runNo = 0;
        static object lockobj = new object();
        //  static int runNoaa = 0;
        public void getPortDataList(object obj, string portName, int baudRate, string sendData)
        {

            //if((serialList.Count == 0))
            //{
            //    runNo = 0;
            //}
            //runNo = runNo + 1;
            ModelRS485QueueList parameter = new ModelRS485QueueList();
            parameter.portName = portName;
            parameter.baudRate = baudRate;
            parameter.sendData = sendData;
            parameter.runNo = runNo;// Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            parameter.content = obj;
            serialList.Add(parameter);
            if (runing == true)
            {
                return;
            }
            lock (lockobj)
            {
                runing = true;
                Console.WriteLine("");
                Console.WriteLine("--------------aaaaaaaaaaa------------------");
                Console.WriteLine("");

                //   while (serialList.Count > 0)
                //  {
                try
                {
                    foreach (ModelRS485QueueList modelCommandAgreementParameter in serialList.ToArray())
                    {
                        Console.WriteLine("");
                        Console.WriteLine("=====" + serialList.Count + "========");
                        Console.WriteLine("");
                        // ModelRS485QueueList modelCommandAgreementParameter = serialList.OrderBy(c=>c.runNo).FirstOrDefault();
                        MQReqModel<object> mQReqModel = (MQReqModel<object>)modelCommandAgreementParameter.content;
                        CommandLogModel commandLogModel = mQReqModel.toGateWayData;
                        // try
                        //  {
                        //if (commandLogModel.key == "getCount")
                        //{
                        //    runNoaa = runNoaa + 13;
                        //    Console.WriteLine("");
                        //    Console.WriteLine("--------------" + runNoaa.ToString() + "--------------------");
                        //    Console.WriteLine("");
                        //}
                        //-----------
                        string result = new UtilsSerial().getPortData(modelCommandAgreementParameter.portName, modelCommandAgreementParameter.baudRate, modelCommandAgreementParameter.sendData);

                        ModelReceverData modelDeviceData = new ModelReceverData();
                        //-------
                        List<ModelCommandResult> commandResults = new List<ModelCommandResult>();
                        ModelCommandResult commandResult = new ModelCommandResult();
                        commandResult.name = commandLogModel.name;
                        commandResult.key = "result";
                        commandResult.value = result;
                        commandResults.Add(commandResult);
                        modelDeviceData.commandResults = commandResults;
                        //------------
                        //modelDeviceData.content = result;
                        mQReqModel.respCode = ResponseCode.SUCCESS;
                        mQReqModel.respMsg = MQEventEnum.Event_State_OK;
                        mQReqModel.toServerData = modelDeviceData;
                        new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                        // }
                        // catch (Exception ex)
                        //  {
                        //      Console.WriteLine(ex.Message);
                        //  }
                        //-----------------
                        serialList.Remove(modelCommandAgreementParameter);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                //}
                runing = false;
            }

        }
        public void executeRS485ToGateWay22(object obj)
        {
            MQReqModel<object> mQReqModel = (MQReqModel<object>)obj;
            CommandLogModel commandLogModel = mQReqModel.toGateWayData;
            ModelSht30Info modelSht30Info = new ModelSht30Info();

            ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);
            ModelCommandAgreementConent modelCommandAgreementConent = UtilsObject.DynamicToEntity<ModelCommandAgreementConent>(modelCommandAgreement.content);
            ModelCommandAgreementParameter modelCommandAgreementParameter = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreement.agreementParameter);

            if (modelCommandAgreement.agreementParameter.command != null)
            {
                List<ModelCommandAgreementParameterCommand> commandList = UtilsObject.DynamicToEntity<List<ModelCommandAgreementParameterCommand>>(modelCommandAgreement.agreementParameter.command);
                if (commandList.Count > 0)
                {
                    ModelCommandAgreementParameterCommand command = commandList.Where(c => c.key == commandLogModel.key).FirstOrDefault();

                    if (command != null)
                    {
                        commandLogModel.content = command.value;//自定指令   否则使用默认commandLogModel.content指令
                    }
                }
            }

            try
            {

                if (commandLogModel.agreementType == EnumAgreementType.RS485)
                {
                    ModelReceverData modelDeviceData = new ModelReceverData();
                    modelDeviceData.content = new UtilsSerial().getPortData(modelCommandAgreementParameter.portName, modelCommandAgreementParameter.baudRate, commandLogModel.content);
                    mQReqModel.respCode = ResponseCode.SUCCESS;
                    mQReqModel.respMsg = MQEventEnum.Event_State_OK;
                    mQReqModel.toServerData = modelDeviceData;
                    new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                    Console.WriteLine(JsonConvert.SerializeObject(mQReqModel));
                }
            }
            catch (Exception ex)
            {

                //new GatewayFileHelper().log_WriteMessageAppend("error", "" + ex.ToString());
                Console.WriteLine(ex.ToString());
            }
        }



    }

}
